package com.example.month11.festivalsms;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.month11.festivalsms.bean.Festival;
import com.example.month11.festivalsms.bean.FestivalLab;
import com.example.month11.festivalsms.bean.Msg;
import com.example.month11.festivalsms.bean.SendedMsg;
import com.example.month11.festivalsms.biz.SmsBiz;
import com.example.month11.flowlayout.view.FlowLayout;
import com.example.recyclerview01.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.HashMap;
import java.util.HashSet;
import java.util.zip.Inflater;

public class SendMsgActivity extends AppCompatActivity {
    public static final String KEY_Festival_id = "festivalId";
    public static final String KEY_msgId = "msgId";
    public static final int CODE_REQUEST = 90;

    private int mFestivalId;
    private int mMsgId;
    private Festival mFestival;
    private Msg mMsg;

    private EditText mEdMsg;
    private Button mBtnAdd;
    private FlowLayout mFlContacts;
    private FloatingActionButton mFabSend;
    private View mLayoutLoading;

    private HashSet<String> mContactNames = new HashSet<>();
    private HashSet<String> mContactNums = new HashSet<>();
    private LayoutInflater mInflater;

    // 监听短信发送的状态
    public static final String ACTION_SEND_MSG = "ACTION_SEND_MSG";
    public static final String ACTION_DELIVER_MSG = "ACTION_DELIVER_MSG";
    private PendingIntent mSendPi;
    private PendingIntent mDeliverPi;
    private BroadcastReceiver mSendBroadcastReceiver;
    private BroadcastReceiver mDeliverBroadcastReceiver;

    private SmsBiz mSmsBiz;
    private int mMsgSendCount = 0; // 发送短信的数量
    private int mMsgTotalCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_msg);
        mInflater = LayoutInflater.from(this);
        mSmsBiz = new SmsBiz(this);

        initDatas();
        initViews();
        initEvents();

        initReceivers();
    }

    private void initReceivers() {
        Intent sendIntent = new Intent(ACTION_SEND_MSG);
        mSendPi = PendingIntent.getBroadcast(this, 0, sendIntent, 0);
        Intent deliverIntent = new Intent(ACTION_DELIVER_MSG);
        mDeliverPi = PendingIntent.getBroadcast(this, 0, deliverIntent, 0);

        // 广播监听短信的发送
        registerReceiver(mSendBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (getResultCode() == RESULT_OK) {
                    Log.e("TAG", "短信发送成功了");

                } else {
                    Log.e("TAG", "短信发送失败了");
                }
                mMsgSendCount++;
                String toast = mMsgSendCount + "/" + mMsgTotalCount + " 短信发送成功";
                Toast.makeText(SendMsgActivity.this, toast, Toast.LENGTH_SHORT).show();
                if (mMsgSendCount == mMsgTotalCount) {
                    finish(); // 发送完了，页面回退。
                }
            }
        }, new IntentFilter(ACTION_SEND_MSG));

        // 监听联系人是否成功接收到短信了。
        registerReceiver(mDeliverBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.e("TAG", "联系人是否成功接收到短信了。");
            }
        }, new IntentFilter(ACTION_DELIVER_MSG));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mSendBroadcastReceiver);
        unregisterReceiver(mDeliverBroadcastReceiver);
    }

    private void initDatas() {
        mFestivalId = getIntent().getIntExtra(KEY_Festival_id, -1);
        mMsgId = getIntent().getIntExtra(KEY_msgId, -1);
        mFestival = FestivalLab.getInstance().getFestivalById(mFestivalId);
        setTitle(mFestival.getName());
        if (mMsgId != -1) {
            mMsg = FestivalLab.getInstance().getMsgByMsgId(mMsgId);
        }
    }

    private void initEvents() {
        mBtnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 选择联系人
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, CODE_REQUEST);
            }
        });

        mFabSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 发送短信。
                if (mContactNums.size() == 0) {
                    Toast.makeText(SendMsgActivity.this, "请先选择联系人", Toast.LENGTH_SHORT).show();
                    return;
                }
                String context = mEdMsg.getText().toString().trim();
                if (TextUtils.isEmpty(context)) {
                    Toast.makeText(SendMsgActivity.this, "请先输入短信内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                mLayoutLoading.setVisibility(View.VISIBLE);
                SendedMsg msg = buildSendedMsg(context);
                mMsgTotalCount = mSmsBiz.sendMsg(mContactNums, msg, mSendPi, mDeliverPi);
                mMsgSendCount = 0;
            }
        });
    }

    // 构建发送的短信记录Bean
    private SendedMsg buildSendedMsg(String context) {
        SendedMsg sendedMsg = new SendedMsg();
        sendedMsg.setMsg(context);
        sendedMsg.setFestivalName(mFestival.getName());
        String names = "";
        for (String name : mContactNames) {
            names += name + ":";
        }
        String numbers = "";
        for (String number : mContactNums) {
            numbers += number + ":";
        }
        // 去掉最后一个:
        sendedMsg.setNames(names.substring(0, names.length() - 1));
        sendedMsg.setNumbers(numbers.substring(0, numbers.length() - 1));
        return sendedMsg;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST && resultCode == RESULT_OK) {
            Uri contactUri = data.getData();
            Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
            cursor.moveToFirst();
            String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            String number = getContactNumber(cursor);
            if (!TextUtils.isEmpty(number)) {
                mContactNums.add(number);
                mContactNames.add(contactName);
                addTag(contactName);
            }
        }
    }

    private void addTag(String contactName) {
        TextView tv = (TextView) mInflater.inflate(R.layout.tag, mFlContacts, false);
        tv.setText(contactName);
        mFlContacts.addView(tv);
    }

    private String getContactNumber(Cursor cursor) {
        String number = null;
        int numCount = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
        if (numCount > 0) { // 有电话号码
            int contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId,
                    null, null);
            phoneCursor.moveToFirst();

            number = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            phoneCursor.close();
        }
        cursor.close();
        return number;
    }


    private void initViews() {
        mEdMsg = findViewById(R.id.id_et_content);
        mBtnAdd = findViewById(R.id.id_btn_add);
        mFlContacts = findViewById(R.id.id_fl_contacts);
        mFabSend = findViewById(R.id.id_fbs_send);
        mLayoutLoading = findViewById(R.id.id_layout_loading);
        mLayoutLoading.setVisibility(View.GONE);

        if (mMsg != null) {
            mEdMsg.setText(mMsg.getContent());
        }
    }

    public static void toActivity(Context context, int festivalId, int msgId) {
        Intent intent = new Intent(context, SendMsgActivity.class);
        intent.putExtra(KEY_Festival_id, festivalId);
        intent.putExtra(KEY_msgId, msgId);
        context.startActivity(intent);
    }


}